package com.example.gulimall.common.server;

import com.example.gulimall.common.perporties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
/**
 * <p>@description: 认证服务器  </p>
 * <p>@author: JGD </p>
 * <p>@create: 2020/3/17 16:57 </p>
 * <p>@version : 2.0.0
 **/
@Configuration
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private TokenStore tokenStore;
    @Autowired(required = false)
    private JwtAccessTokenConverter jwtAccessTokenConverter;
//    @Resource
//    private UserAuthService userDetailServcie;
    @Resource
    private SecurityProperties securityProperties;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //设置client
        clients.inMemory()
                .withClient(securityProperties.getClientId())
                .secret(securityProperties.getSecret())
                .accessTokenValiditySeconds(securityProperties.getAccessTokenExpireSecond())
                .authorizedGrantTypes("password")
                .scopes("all");


    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //密码模式必须添加authenticationManager
        endpoints.authenticationManager(authenticationManager);
        endpoints.tokenStore(tokenStore);
//        endpoints.userDetailsService(userDetailServcie);
        if (jwtAccessTokenConverter!=null){
            endpoints.accessTokenConverter(jwtAccessTokenConverter);
        }
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("isAuthenticated()");
    }
}